package logic

import (
	"common/global"
	"common/model"
	"context"
	"fmt"
	product "product_server/proto"
	"time"
)

// ProductList 商品列表展示
func (p *ProductServer) ProductList(ctx context.Context, req *product.ProductListRequest) (*product.ProductListResponse, error) {
	query := global.Db.Model(&model.MedicalProduct{})
	page := req.Pages
	if page <= 0 {
		page = 1
	}
	pageSize := req.PagePerNums
	if pageSize <= 0 {
		pageSize = 10
	}
	//关键字搜索
	if req.Keyword != "" {
		_, err := model.KeyWordsQuery(req.Keyword, query)
		if err != nil {
			return nil, err
		}
	}
	//是否是新品（一个月内发布）
	if req.IsNew != 0 {
		oneMonthAgo := time.Now().AddDate(0, -1, 0)
		_, err := model.NewQuery(oneMonthAgo, query)
		if err != nil {
			return nil, err
		}
	}
	//最低价
	if req.PriceMin > 0 {
		query = query.Where("price >= ?", req.PriceMin)
	}
	//最高价
	if req.PriceMax > 0 {
		query = query.Where("price <= ?", req.PriceMax)
	}
	//按分类查询
	if req.TopCategory > 0 {
		categoryLevel, err := model.Scan(req.TopCategory)
		if err != nil {
			return nil, err
		}
		fmt.Println("categoryLevel", categoryLevel)
		if categoryLevel == 0 {
			subCategoryIDs, err := model.Pluck(req.TopCategory)
			if err != nil {
				return nil, err
			}
			fmt.Println(subCategoryIDs)
			_, err = model.ProductCateList(subCategoryIDs, query)
			if err != nil {
				return nil, err
			}
		} else {
			query = query.Where("cate_id = ?", req.TopCategory)
		}
	}

	// 先获取总数（在应用分页之前）
	var total int64
	query.Count(&total)

	// 然后应用分页获取数据
	offset := (page - 1) * pageSize
	productList, err := model.ProductList(query, offset, pageSize)
	if err != nil {
		return nil, err
	}
	var goodsItem []*product.ProductListItem
	for _, storeProduct := range productList {
		goodsItem = append(goodsItem, &product.ProductListItem{
			Id:        storeProduct.Id,
			CateId:    storeProduct.CateId,
			StoreName: storeProduct.StoreName,
			Browse:    storeProduct.Browse,
			Sales:     storeProduct.Sales,
			Collect:   storeProduct.Collect,
			StoreInfo: storeProduct.StoreInfo,
			Image:     storeProduct.Image,
			Price:     storeProduct.Price,
		})
	}

	response := &product.ProductListResponse{
		Total: total,
		List:  goodsItem,
	}
	return response, nil
}
